//
//  UIUtils.m
//  lvgouProjectIphone
//
//  Created by 张明磊 on 14-3-26.
//  Copyright (c) 2014年 lvgou. All rights reserved.
//

#import "UIUtils.h"
#import "MBHUDView.h"
#import "MBProgressHUD.h"
#import <CoreText/CoreText.h>
#import <mach/mach_time.h>
#include <sys/sysctl.h>

@implementation UIUtils

void(* loadingFounction)(id, SEL ,id);

#pragma mark - 非动态绑定,直接地址调用函数 -
/**
 *  非动态绑定
 直接地址调用函数,适用于重复调用的函数可用此for循环
 *  @param class_name       类名
 *  @param function_name 函数名
 *  @param model               函数参数
 */
+ (void)useClass:(id)class_name loadFountion:(NSString *)function_name andParameter:(id)model
{
    SEL class_sel = NSSelectorFromString(function_name);
    IMP class_imp = [class_name methodForSelector:class_sel];
    loadingFounction = (void(*)(id, SEL, id))class_imp;
    loadingFounction(class_name,class_sel,model);
}

#pragma mark - 获取当前时间 -
/**
 *  获取当前时间
 *  @return string
 */
+ (NSString *)getCurrentDateString{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-ddHH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //alloc后对不使用的对象别忘了release
    //[dateFormatter release];
    return currentDateStr;
}

#pragma mark - 获取距离目标时间 -
/**
 *   获取距离目标时间
 *  @param seconds 目标时间
 *  @return string
 */
+ (NSString*)getDateStringAfterSeconds:(NSTimeInterval)seconds
{
    NSDate *destDate = [NSDate dateWithTimeIntervalSinceNow:seconds];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *dateStr = [dateFormatter stringFromDate:destDate];
    //alloc后对不使用的对象别忘了release
    //[dateFormatter release];
    return dateStr;
}

#pragma mark - 获取Decoument目录 -
/**
 *   获取Decoument目录
 *
 *  @return string
 */
+ (NSString*)getDocumentDirName
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

#pragma mark - 渐变消失 -
/**
 *  渐变消失
 *
 *  @param view 目标View
 */
+ (void)hiddeView:(UIView *)view
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:1.0];
    [view setAlpha:0.0f];
    [UIView commitAnimations];
}

#pragma mark - 渐变显示 -
/**
 *  渐变显示
 *
 *  @param view 目标View
 */
+ (void)showView:(UIView *)view
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:1.0];
    [view setAlpha:1.0f];
    [UIView commitAnimations];
}

#pragma mark - 从时间戳获取时间 -
/**
 *  从时间戳获取时间
 *
 *  @param string_timeStamp 时间戳
 *
 *  @return 时间
 */
+ (NSString *)getTimeFromTimeStamp:(NSString *)string_timeStamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.YYYY-MM-dd HH:mm:ss
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    //NSDate* date = [formatter dateFromString:timeStr];
    //------------将字符串按formatter转成nsdate
    //NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    //NSString *nowtimeStr = [formatter stringFromDate:datenow];
    //----------将nsdate按formatter格式转成nsstring
    //时间转时间戳的方法:
    //NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[datenow timeIntervalSince1970]];
    //NSLog(@"timeSp:%@",timeSp);
    //时间戳转时间的方法
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[string_timeStamp integerValue]];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}


#pragma mark - 等待弹窗 -
/**
 *  等待弹窗
 *
 *  @param _infoContent     内容
 *  @param time                   等待时间
 */
+ (void)showHUD:(NSString *)_infoContent afterTime:(float)time{
    [MBHUDView hudWithBody:_infoContent type:MBAlertViewHUDTypeActivityIndicator hidesAfter:time show:YES];
}

#pragma mark - 提示弹窗 -
/**
 *  提示弹窗
 *
 *  @param _infoContent     内容
 *  @param time                   等待时间
 */
+ (void)showAlterView:(NSString *)_infoContent afterTime:(float)time
{
    [MBHUDView hudWithBody:_infoContent type:MBAlertViewHUDTypeDefault hidesAfter:time show:YES];
}

#pragma mark - 显示等待框 -
/**
 *  显示等待框
 *
 *  @param string_content 内容
 *  @param view_cover 为可点击层,如果为nil,则为全屏遮罩
 */
+ (void)showHUDWithContent:(NSString *)string_content inCoverView:(UIView *)view_cover
{
    if(view_cover)
    {
        [MBHUDView hudWithBody:string_content type:MBAlertViewHUDTypeActivityIndicator hidesAfter:888.0f show:YES inCoverView:view_cover];
    }
    else
    {
        [MBHUDView hudWithBody:string_content type:MBAlertViewHUDTypeActivityIndicator hidesAfter:888.0f show:YES];
    }
}

#pragma mark - 消除等待框 -
/**
 *  消除等待框
 */
+ (void)dismissCurrentHUD
{
    [MBHUDView dismissCurrentHUD];
}

#pragma mark - 检测网络 -
/**
 *  检测网络
 *
 *  @return BOOL
 */
+ (BOOL)isConnectNetwork
{
    BOOL connect_result = YES;
    /*Reachability *connect_net = [Reachability reachabilityWithHostname:@"www.baidu.com"];
     switch ([connect_net currentReachabilityStatus])
     {
     case NotReachable:
     {
     connect_result = NO;
     }break;
     case ReachableViaWWAN:
     {
     connect_result = YES;
     }break;
     case ReachableViaWiFi:
     {
     connect_result = YES;
     }break;}*/
    return connect_result;
}

#pragma mark - 压缩图片尺寸 -
/**
 *  压缩图片尺寸
 适用于上传图片
 *
 *  @param image   源图片
 *  @param newSize 目标尺寸
 *
 *  @return image
 */
+ (UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - 压缩图片大小 -
/**
 *  压缩图片大小
 适用于服务器上传图片
 *
 *  @param tempImage 源图片
 *  @param imageName 保存位置,为空则不保存
 *
 *  @return string
 */
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(tempImage,1);
    if(imageData.length/1000 > 2000)
    {
        for(int i = 0; imageData.length < 2000; i++)
        {
            imageData = UIImageJPEGRepresentation(tempImage,1 - 0.1*i);
        }
    }
    NSString *fullPathToFile;
    if(imageName)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
        [imageData writeToFile:fullPathToFile atomically:NO];
        //NSLog(@"%d",imageData.length/1000);
    }
    return fullPathToFile;
}

#pragma mark - 进入动画 -
/**
 *  进入动画
 *  进入前设置好view位置
 *  @param view 操作view
 */
+ (void)addViewWithAnimation:(UIView *)view
{
    [UIView animateWithDuration:0.2f animations:
     ^{
         [UIView beginAnimations:nil context:nil];
         [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
         [UIView setAnimationDuration:0.2f];
         [UIView setAnimationRepeatCount:1];
         [UIView setAnimationBeginsFromCurrentState:YES];
         [view setCenter:CGPointMake(view.center.x - view.frame.size.width, view.center.y)];
         [UIView commitAnimations];
     }completion:^(BOOL finish){if(finish){
         
     }}];
}

#pragma mark - 移出动画 -
/**
 *  移出动画
 *
 *  @param view 源view
 */
+ (void)removedViewWithAnimation:(UIView *)view
{
    [UIView animateWithDuration:0.2f animations:
     ^{
         [UIView beginAnimations:nil context:nil];
         [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
         [UIView setAnimationDuration:0.2f];
         [UIView setAnimationRepeatCount:1];
         [UIView setAnimationBeginsFromCurrentState:YES];
         [view setCenter:CGPointMake(view.center.x + view.frame.size.width, view.center.y)];
         [UIView commitAnimations];
     }completion:^(BOOL finish){
         if(finish)
         {
             double delayInSeconds = 1;
             dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
             dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                 [view removeFromSuperview];
             });
         }
     }];
}

#pragma mark - 按类型提示 -
/**
 *  按类型提示
 *
 *  @param _infoContent 按类型提示
 *  @param view         出现view
 *  @param type         HUB类型
 */
+ (void)view_showProgressHUD:(NSString *)_infoContent inView:(UIView *)view withType:(NSInteger )type
{
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    progressHUD.yOffset = -40;
    //[progressHUD setCenter:CGPointMake(progressHUD.center.x, progressHUD.center.y -20)];
    [progressHUD setAnimationType:MBProgressHUDAnimationZoom];
    switch (type)
    {
        case 0:
        {
            [progressHUD setMode: MBProgressHUDModeIndeterminate];
        }break;
        case 1:
        {
            [progressHUD setMode:MBProgressHUDModeCustomView];
            UIView *view_back = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
            [view_back setBackgroundColor:[UIColor clearColor]];
            [progressHUD setCustomView:view_back];
        }break;
        default:
            break;
    }
    [progressHUD setLabelText:_infoContent];
    [progressHUD setLabelFont:[UIFont fontWithName:@"Helvetica-Bold" size:20.0]];
    [progressHUD setRemoveFromSuperViewOnHide:YES];
    
    [self performSelector:@selector(view_hideProgressHUDinView:) withObject:view afterDelay:15];
}

#pragma mark - 提示文字信息 -
/**
 *  提示文字信息
 *
 *  @param _infoContent 文字源
 *  @param view         出现view
 *  @param time         提示时长
 */
+ (void)view_showProgressHUD:(NSString *) _infoContent inView:(UIView *)view withTime:(float)time
{
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    progressHUD.yOffset = - 20;
    [progressHUD setAnimationType:MBProgressHUDAnimationZoom];
    UIView *view_back = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    [view_back setBackgroundColor:[UIColor clearColor]];
    [progressHUD setCustomView:view_back];
    [progressHUD setMode:MBProgressHUDModeCustomView];
    [progressHUD setLabelText:_infoContent];
    [progressHUD setLabelFont:[UIFont fontWithName:@"Helvetica-Bold" size:20.0]];
    [progressHUD setRemoveFromSuperViewOnHide:YES];
    [self performSelector:@selector(view_hideProgressHUDinView:) withObject:view afterDelay:time];
}

#pragma mark - HUD消失 -
/**
 *  HUD消失
 *
 *  @param view 所在view
 */
+ (void)view_hideProgressHUDinView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:YES];
}

#pragma mark - 计算字符串高度 -
/**
 *  计算字符串高度
 *
 *  @param string 内容
 *  @param width 固定宽度
 *
 *  @return 高度
 */
+ (int)getAttributedStringHeightWithString:(NSAttributedString *)string  WidthValue:(int) width{
    int total_height = 0;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);    //string 为要计算高度的NSAttributedString
    CGRect drawingRect = CGRectMake(0, 0, width, 1000);  //这里的高要设置足够大
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, drawingRect);
    CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);
    CGPathRelease(path);
    CFRelease(framesetter);
    NSArray *linesArray = (NSArray *) CTFrameGetLines(textFrame);
    CGPoint origins[[linesArray count]];
    CTFrameGetLineOrigins(textFrame, CFRangeMake(0, 0), origins);
    int line_y = (int) origins[[linesArray count] -1].y;  //最后一行line的原点y坐标
    CGFloat ascent;
    CGFloat descent;
    CGFloat leading;
    CTLineRef line = (__bridge CTLineRef) [linesArray objectAtIndex:[linesArray count]-1];
    CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
    total_height = 1000 - line_y + (int) descent +1;    //+1为了纠正descent转换成int小数点后舍去的值
    CFRelease(textFrame);
    return total_height;
}

#pragma mark - 计算方法花费的时间 -
/**
 *  计算方法花费的时间
 *
 *  @param ^blockvoid 传入方法
 *
 *  @return 时间
 */
CGFloat getTimeBlock (void (^block)(void)) {
    mach_timebase_info_data_t info;
    if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;
    uint64_t start = mach_absolute_time ();
    block ();
    uint64_t end = mach_absolute_time ();
    uint64_t elapsed = end - start;
    uint64_t nanos = elapsed * info.numer / info.denom;
    return (CGFloat)nanos / NSEC_PER_SEC;
}

#pragma mark - 多线程执行 -
/**
 *  多线程执行
 *
 *  @param ^blockvoid 传入方法
 */
void runInBackground (void (^block)(void)) {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        block();
    });
}

#pragma mark - 主线程执行UI -
/**
 *  主线程执行UI
 *
 *  @param ^blockvoid 传入方法
 */
void runInBackgroundMainUI (void (^block)(void)){
    dispatch_async(dispatch_get_main_queue(), ^{
        block();
    });
}

#pragma mark - 判断是否中文 -
/**
 *  判断是否中文
 */
+ (BOOL)isChinese{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if([currentLanguage isEqualToString:@"zh-Hans"]){
        return YES;
    }
    else{
        return NO;
    }
}

#pragma mark - 获取屏幕宽度 -
/**
 *  获取屏幕宽度
 */
+ (NSInteger)windowWidth{
    return [[[[UIApplication sharedApplication] windows] objectAtIndex:0] frame].size.width;
}

#pragma mark - 获取屏幕高度 -
/**
 *  获取屏幕高度
 */
+ (NSInteger)windowHeight {
    return [[[[UIApplication sharedApplication] windows] objectAtIndex:0] frame].size.height;
}

#pragma mark - 检测是否有app -
/**
 *  检测是否有app
 */
+ (NSArray *)checkHasOwnApp{
    NSArray *mapSchemeArr = @[@"comgooglemaps://",@"iosamap://navi",@"baidumap://map/"];
    NSMutableArray *appListArr = [[NSMutableArray alloc] initWithObjects:@"系统地图", nil];
    for (int i = 0; i < [mapSchemeArr count]; i++) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[mapSchemeArr objectAtIndex:i]]]]) {
            if (i == 0) {
                [appListArr addObject:@"google地图"];
            }else if (i == 1){
                [appListArr addObject:@"高德地图"];
            }else if (i == 2){
                [appListArr addObject:@"百度地图"];
            }
        }
    }
    return appListArr;
}

#pragma mark - 减少第一次弹出键盘所花时间 -
/**
 *  减少第一次弹出键盘所花时间
 */
+ (void)cutInputTextTime{
    static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
        UITextField *text_input = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        UIView *view_input = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
        [view_input addSubview:text_input];
        [text_input becomeFirstResponder];
        [text_input resignFirstResponder];
        [text_input removeFromSuperview];
    });
}

#pragma mark - 正则判断手机号 -
/**
 *  正则判断手机号
 */
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,181,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[01235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188,178
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378]|78)\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186,176
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56]|76)\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,181,189,177
     22         */
    NSString * CT = @"^1((33|53|8[019]|77)[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark - 判断推送权限 -
/**
 *  判断推送权限
 */
+ (int)pushPower{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        UIUserNotificationType types;
        types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
        return (types & UIRemoteNotificationTypeAlert);
    }
    else{
        UIRemoteNotificationType types;
        types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        return (types & UIRemoteNotificationTypeAlert);
    }
}

#pragma mark - 判断是否第一次登陆 -
/**
 *  判断是否第一次登陆
 */
+ (BOOL)isFirstLogin{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *string_everLaunched = [NSString stringWithFormat:@"everLaunched%@",app_Version];
    NSString *string_firstLaunch = [NSString stringWithFormat:@"firstLaunch%@",app_Version];
    if (![[NSUserDefaults standardUserDefaults] boolForKey:string_everLaunched]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:string_everLaunched];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:string_firstLaunch];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:string_firstLaunch];
    }
    return [[NSUserDefaults standardUserDefaults] boolForKey:string_firstLaunch];
}

#pragma mark - 计算字的高度 -

+ (float)heightFor:(NSString *)str withFont:(UIFont *)font labWidth:(float)width
{
    //    NSString * deviceType = [UIDevice currentDevice].model;
    
    CGSize asize = CGSizeMake(width,2000);
    CGSize labelsize = CGSizeMake(0, 0);
    if (IOS6_VERSION) {
        labelsize = [str sizeWithFont:font constrainedToSize:asize lineBreakMode:NSLineBreakByWordWrapping];
    }
    else
    {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
        labelsize = [str boundingRectWithSize:asize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    }
    
    return labelsize.height;
}

+ (CGSize)cgrectFor:(NSString *)str withFont:(UIFont *)font labWidth:(float)width;
{
    CGSize asize = CGSizeMake(width,2000);
    CGSize labelsize = CGSizeMake(0, 0);
    if (IOS6_VERSION) {
        labelsize = [str sizeWithFont:font constrainedToSize:asize lineBreakMode:NSLineBreakByWordWrapping];
    }
    else
    {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
        labelsize = [str boundingRectWithSize:asize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    }
    
    return labelsize;

}
#pragma mark - 设备型号
+ (NSString *)currentDevicePlatformString
{
    // Gets a string with the device model
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5 (GSM)";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (UK+Europe+Asis+China)";
    if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (UK+Europe+Asis+China)";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WIFI)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini (GSM)";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3 (CDMA)";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (Wifi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    
    return platform;
}

#pragma mark - 基础控件的创建 -

+ (UIButton *)creatButtonAddAction:(SEL)select andTarget:(id)target;
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:target action:select forControlEvents:UIControlEventTouchUpInside];
    return btn;
    
}

+ (UIImageView *)creatImageView
{
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectZero];
    return imageview;
}

+ (UILabel *)creatLabel
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.backgroundColor = [UIColor clearColor];
    label.font = FontOfHelveticaBold(16);
    return label;
}

#pragma mark - 返回问题详细类型 -

+ (NSArray *)getQuestionTypeWithkind:(NSInteger)num
{
    NSString *qType = nil;
    NSString *qDetalType = nil;
    if(num < 10){
        qType = @"个人问题";
    }
    else{
        qType = @"公司问题";
    }
    
    switch (num) {
        case 0:{
            qDetalType = @"婚姻家庭";
        }break;
        case 1:{
            qDetalType = @"房屋买卖";
        }break;
        case 2:{
            qDetalType = @"债务纠纷";
        }break;
        case 3:{
            qDetalType = @"劳动争议";
        }break;
        case 4:{
            qDetalType = @"交通肇事";
        }break;
        case 5:{
           qDetalType = @"刑事案件";
        }break;
        case 6:{
            qDetalType = @"其他类型";
        }break;
        case 7:{
            qDetalType = @"医疗纠纷";
        }break;
        case 11:{
            qDetalType = @"公司注册";
        }break;
        case 12:{
            qDetalType = @"投资融资";
        }break;
        case 13:{
            qDetalType = @"股权期权";
        }break;
        case 14:{
            qDetalType = @"合同事项";
        }break;
        case 15:{
            qDetalType = @"知识产权";
        }break;
        case 16:{
            qDetalType = @"财税事务";
        }break;
        case 17:{
            qDetalType = @"劳动人事";
        }break;
        case 18:{
            qDetalType = @"债务纠纷";
        }break;
        case 19:{
            qDetalType = @"其他问题";
        }break;
        default:
            break;
    }
    
    NSArray *arr = [NSArray arrayWithObjects:qType,qDetalType, nil];
    return arr;
}


@end

#pragma mark UIView (UIUtils)

@implementation UIView (UIUtils)

- (void)roundedViewWithRadius:(CGFloat)radius
{
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = radius;
}

- (UIImage *)toImage
{
    float scale = [[UIScreen mainScreen] scale];
    CGSize size = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, YES, scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)setFrameLeft:(CGFloat)left
{
    CGRect frame = self.frame;
    frame.origin.x = left;
    self.frame = frame;
}

- (void)setFrameTop:(CGFloat)top
{
    CGRect frame = self.frame;
    frame.origin.y = top;
    self.frame = frame;
}

- (void)setFrameOrigin:(CGFloat)left top:(CGFloat)top
{
    CGRect frame = self.frame;
    frame.origin.x = left;
    frame.origin.y = top;
    self.frame = frame;
}

- (void)setFrameHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (void)setFrameWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (void)setFrameSize:(CGFloat)height width:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.height = height;
    frame.size.width = width;
    self.frame = frame;
}

- (void)setFrameSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (void)fillSuperView
{
    UIView *sv = self.superview;
    if (sv != nil)
    {
        CGRect rect = CGRectZero;
        rect.size = sv.frame.size;
        self.frame = rect;
    }
}

- (void)setTapActionWithTarget:(id)target selector:(SEL)selector
{
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:target action:selector];
    [self addGestureRecognizer:gr];
}

- (void)borderRed
{
    [self.layer setBorderColor:[UIColor redColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderOrange
{
    [self.layer setBorderColor:[UIColor orangeColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderYellow
{
    [self.layer setBorderColor:[UIColor yellowColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderGreen
{
    [self.layer setBorderColor:[UIColor greenColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderCyan
{
    [self.layer setBorderColor:[UIColor cyanColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderBlue
{
    [self.layer setBorderColor:[UIColor blueColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderPurple
{
    [self.layer setBorderColor:[UIColor purpleColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderBlack
{
    [self.layer setBorderColor:[UIColor blackColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderWhite
{
    [self.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.layer setBorderWidth:1];
}

- (void)borderGray
{
    [self.layer setBorderColor:[UIColor grayColor].CGColor];
    [self.layer setBorderWidth:1];
}

@end
